
const {createSocket} = require('node:dgram')
const WebSocket  = require('ws')

const target_mcu_ip ='200.200.200.11'       //通信对端单片机的IP地址
const local_ip = '200.200.200.35'            //绑定的本端IP地址

const WebSocketServer = WebSocket.Server;

const wss =new WebSocketServer({ port:10088 },(err)=>{
	if(!err){
		console.log("Websocket Server启动运行了,监听端口 10088 .....")
	}
})

//如果有WebSocket请求接入，wss对象可以响应connection事件来处理这个WebSocket：
wss.on('connection',function(ws,req){  //在connection事件中，回调函数会传入一个WebSocket的实例，表示这个WebSocket连接。
    console.log(`[SERVER] connection()`);
	console.log(req.url)
	if(req.url.match(/m32_cmd/)){
		setup_m32_urt1_conn(ws)
	}
	
	if(req.url.match(/ins_data/)){
		setup_uart4_conn(ws)
	}
	
})

function heartBeat(ws){
	this.isAlive = true
}

//保存所有连接到uart1通道的客户端连接
const parser1_conn=[]
function setup_m32_urt1_conn(ws){
	console.log("Setup事件处理函数for new connection~~ ",ws.readyState)
	
	ws.on('message',(msg)=>{
		console.log(`[Shell sock][${Date().substring(0,24)}]Xfer2MCU:`,msg.length, msg);
        //port1.write(msg)
        udp_ch1.send(msg)
	})
	
	ws.on('close',()=>{
		
	})
	
	ws.on('pong',heartBeat)
	
	ws.on('error',(err)=>{
		console.error(err,err.code)
	})
	
	ws.isAlive = true 
	
	parser1_conn.push(ws)
}


// 保存所有连接到Uart4通道的客户端连接
const parser2_conn = []

function setup_uart4_conn(ws){
    console.log("Setup事件处理函数for新连接~~ ",ws.readyState)
    
	ws.on('message',(msg)=>{
		console.log(`[指令sock][${Date().substring(0,24)}]Xfer->MCU:`,msg.length,msg)
        //port4.write(msg)
        udp_ch2.send(msg)
	})
	
    ws.on('close',()=>{
        
    })
    
    ws.on('pong',heartBeat)
    
    ws.on('error',(err)=>{
        console.error(err,err.code)
    })
    
    ws.isAlive = true 
    
    parser2_conn.push(ws)
}



const udp_ch1 = createSocket('udp4')
udp_ch1.on('error',err=>{
    console.log('udp ch1 to 控制台sock出错',err)
})
udp_ch1.on('message',(msg,rinfo)=>{
    //console.log(`[COM sock][${Date().substring(0,24)}]MCU->上位机 len=`,msg.length,msg)
    parser1_conn.forEach((conn,index,arr)=>{
        if(conn && conn.readyState==1){
            conn.send(msg,err=>{
                if(err) console.error(`[uart1 proxy] Error:${err}`)
            })
        }
    })
})
udp_ch1.bind(5100,local_ip)
udp_ch1.connect(5000,target_mcu_ip)


const udp_ch2 = createSocket('udp4')
udp_ch2.on('error',err=>{
    console.log('udp ch2 to 私有协议端口出错',err)
})
 let cnt=0    //收到并转发的消息包数
 let total=0  //收到并转发的消息总长度
udp_ch2.on('message',(msg,rinfo)=>{
    cnt++
    total += msg.length  
    if(cnt % 1000 == 0){
        console.log('[MCU指令sock]转发给上位机 数据总量:',total,`|${Date().substring(0,24)}`)
    }
    parser2_conn.forEach((ws,index,arr)=>{
        if(ws && ws.readyState==1){
            ws.send(msg,err=>{
                if(err) console.warn(`[Uart4 proxy] Transfer data Error:${err}`)
            })
        }
    })
})
udp_ch2.bind(6100,local_ip)
udp_ch2.connect(6000,target_mcu_ip)

